package com.example.eletech;


import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import XMLReader.Driver;
import android.app.Activity;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.AvoidXfermode.Mode;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.eletech.R;
import controller.*;

public class MainActivity extends Activity implements OnClickListener 
{
	private String[] data;// = {"one", "two", "three", "four", "five"};
	private Button btn0;
	private Button btn1;
	private Button btn2;
	private Button btn3;
	private Button btn4;
	private Button btnClean;
	private Button btnSet;
	private TextView txtProblem;
	private Spinner spinner;
	private ControllerErrorBtn cer;
	private List<String> linesList;
	private boolean xmlReadStatus;
	private ModelController controller;
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        controller =ModelController.getModelController();
        cer=new ControllerErrorBtn();
        linesList= new ArrayList<String>();
        if(readXML())
        	xmlReadStatus=true;
        else
        	xmlReadStatus=false;
        // адаптер        
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data);        
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
        spinner = (Spinner) findViewById(R.id.spinner);
        spinner.setAdapter(adapter); 
        btn0=(Button)findViewById(R.id.btn0);
        btn0.setOnClickListener(this);
        btn1=(Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(this);
        btn2=(Button)findViewById(R.id.btn2);
        btn2.setOnClickListener(this);
        btn3=(Button)findViewById(R.id.btn3);
        btn3.setOnClickListener(this);
        btn4=(Button)findViewById(R.id.btn4);
        btn4.setOnClickListener(this);
        btnClean=(Button)findViewById(R.id.btnClean);
        btnClean.setOnClickListener(this);
        btn0.setBackgroundColor(Color.GREEN);
        btn1.setBackgroundColor(Color.GREEN);
        btn2.setBackgroundColor(Color.GREEN);
        btn3.setBackgroundColor(Color.GREEN);
        btn4.setBackgroundColor(Color.GREEN);
        btnSet=(Button) findViewById(R.id.btnSet);
        btnSet.setOnClickListener(this);
        txtProblem=(TextView) findViewById(R.id.txtProblem);
        
        //if read xmlfile or vaitation process not accept
        //show error message and close application
        if(!xmlReadStatus)
	        globalErrorApp();
        // заголовок        
        spinner.setPrompt("Firmware version"); 
        
        // выдел�?ем �?лемент         
        spinner.setSelection(0);  
        
        // у�?танавливаем обработчик нажати�?       
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() 
        {      
        	@Override      
        	public void onItemSelected(AdapterView<?> parent, View view,int position, long id) 
        	{       
        		cer.clearAllErrors();
    			btn0.setBackgroundColor(Color.GREEN);
    			btn1.setBackgroundColor(Color.GREEN);
    			btn2.setBackgroundColor(Color.GREEN);
    			btn3.setBackgroundColor(Color.GREEN);
    			btn4.setBackgroundColor(Color.GREEN);
    			txtProblem.setText("All the indicators are turned off, turn ON any indicator and press SET");
        	}      
	        @Override      
	        public void onNothingSelected(AdapterView<?> arg0) 
	        {      }   
    	});    
    }
    
    
    
    //read xml to string, basic parse, forward to controller to parsing, 
    //if not complete or retrive error, return false to stup program
	private boolean readXML() 
    {
		String text;
		try 
		{
	        Resources res = getResources();
	        InputStream in_s = res.openRawResource(R.raw.errors_per_model2);

	        byte[] b = new byte[in_s.available()];
	        in_s.read(b);
	        text=new String(b);
	        
	        //basic parce xml toString
	        if((linesList=lineToList(text)).isEmpty())
        		return false;
	        //forward rawdataList to controller
	        if(!controller.xmlData(linesList))
	        	return false;
	        //Driver driver= new Driver();
	        //driver.readXML(linesList);
	        //linesList=driver.models();
	        //data= new String[linesList.size()];
	        //linesList.toArray(data);
	        data=controller.modelValues();
	        return true;
	        
	    } 
		catch (Exception e) 
		{
	        // e.printStackTrace();
			text="Error: can't show help.";
			return false;
	    }

    }

	private void globalErrorApp()
	{
		Toast.makeText(getBaseContext(),
    			"Database is corrupted! Please tell to technical support", 
    				Toast.LENGTH_LONG).show();
    	this.finish();
	}
	
	//basic parce string by line, return list
	private List<String> lineToList(String text)
	{
		List<String> tmpList=new ArrayList<String>();
		while(text.length()>0)
		{
			int i= text.indexOf("\r\n");
			tmpList.add(text.substring(0, i));
			//String m=text.substring(0, i);
			//System.out.println(text.substring(0, i));
			if(i+3<text.length())
				text=text.substring(i+2);
			else
				text="";
		}
		for(String t:tmpList)
			System.out.println(t);
		
		return tmpList;
	}
	
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


	@Override
	public void onClick(View v) 
	{
		switch (v.getId()) 
		{
		case R.id.btn0:
			btn0.setBackgroundColor(cer.setBtnColor(0));
			break;
		case R.id.btn1:
			btn1.setBackgroundColor(cer.setBtnColor(1));
			break;
		case R.id.btn2:
			btn2.setBackgroundColor(cer.setBtnColor(2));
			break;
		case R.id.btn3:
			btn3.setBackgroundColor(cer.setBtnColor(3));
			break;
		case R.id.btn4:
			btn4.setBackgroundColor(cer.setBtnColor(4));
			break;
		case R.id.btnClean:
			cer.clearAllErrors();
			btn0.setBackgroundColor(Color.GREEN);
			btn1.setBackgroundColor(Color.GREEN);
			btn2.setBackgroundColor(Color.GREEN);
			btn3.setBackgroundColor(Color.GREEN);
			btn4.setBackgroundColor(Color.GREEN);
			txtProblem.setText("All the indicators are turned off, turn ON any indicator and press SET");
			break;
		case R.id.btnSet:
			//txtProblem.setText(setProblemView(cer.getBtnStatus()));
			//txtProblem.setText(controller.errorDescription(spinner.getSelectedItem().toString(), 3))  ;
			int number=controller.selectednumber(cer.getBtnStatus());//convert from binary to integer
			if(number<0 || number>31)//illegal number
				txtProblem.setText("All the indicators are turned off. Please, turn ON any indicator and press SET again");
			else
				txtProblem.setText(controller.errorDescription(spinner.getSelectedItem().toString(), number-1));
			break;
		default:
			break;
		
		}

	}

    private String setProblemView(boolean[] errStatus)
    {
    	String errStatusStr="light enabled :";
    	for(int i=0; i<errStatus.length;i++)
    	{
    		if(errStatus[i])
    			errStatusStr+=i+1+", ";
    	}
    	if(errStatusStr.length()==15)
    		errStatusStr="all light disabled";
    	return errStatusStr;
    }
}
